/*

Copyright (c) 2005-2008, Simon Howard

Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 */

use std::cmp::Ordering;

enum BinaryHeapType {
    Min,
    Max,
}

type BinaryHeapValue = *mut ();

type BinaryHeapCompareFunc = fn(BinaryHeapValue, BinaryHeapValue) -> Ordering;

struct BinaryHeap {
    heap_type: BinaryHeapType,
    values: Vec<BinaryHeapValue>,
    compare_func: BinaryHeapCompareFunc,
}

impl BinaryHeap {
    fn new(heap_type: BinaryHeapType, compare_func: BinaryHeapCompareFunc) -> Option<Self> {
        let heap = BinaryHeap {
            heap_type,
            values: Vec::with_capacity(16),
            compare_func,
        };
        Some(heap)
    }

    fn free(self) {
        // In Rust, memory is automatically freed when the object goes out of scope.
    }

    fn insert(&mut self, value: BinaryHeapValue) -> bool {
        if self.values.len() >= self.values.capacity() {
            self.values.reserve(self.values.capacity());
        }

        self.values.push(value);
        self.percolate_up(self.values.len() - 1);
        true
    }

    fn pop(&mut self) -> BinaryHeapValue {
        if self.values.is_empty() {
            return std::ptr::null_mut();
        }

        let result = self.values[0];
        let last_value = self.values.pop().unwrap();
        if !self.values.is_empty() {
            self.values[0] = last_value;
            self.percolate_down(0);
        }
        result
    }

    fn num_entries(&self) -> usize {
        self.values.len()
    }

    fn binary_heap_cmp(&self, data1: BinaryHeapValue, data2: BinaryHeapValue) -> Ordering {
        match self.heap_type {
            BinaryHeapType::Min => (self.compare_func)(data1, data2),
            BinaryHeapType::Max => (self.compare_func)(data2, data1),
        }
    }

    fn percolate_up(&mut self, index: usize) {
        let mut index = index;
        let value = self.values[index];
        while index > 0 {
            let parent = (index - 1) / 2;
            if self.binary_heap_cmp(self.values[parent], value) == Ordering::Less {
                break;
            }
            self.values[index] = self.values[parent];
            index = parent;
        }
        self.values[index] = value;
    }

    fn percolate_down(&mut self, index: usize) {
        let mut index = index;
        let value = self.values[index];
        loop {
            let child1 = index * 2 + 1;
            let child2 = index * 2 + 2;
            let mut next_index = index;

            if child1 < self.values.len() && self.binary_heap_cmp(value, self.values[child1]) == Ordering::Greater {
                if child2 < self.values.len() && self.binary_heap_cmp(self.values[child1], self.values[child2]) == Ordering::Greater {
                    next_index = child2;
                } else {
                    next_index = child1;
                }
            } else if child2 < self.values.len() && self.binary_heap_cmp(value, self.values[child2]) == Ordering::Greater {
                next_index = child2;
            }

            if next_index == index {
                break;
            }

            self.values[index] = self.values[next_index];
            index = next_index;
        }
        self.values[index] = value;
    }
}